package com.eva.service.common;

import com.eva.framework.common.constants.ResponseStatus;
import com.eva.framework.common.exception.BusinessException;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class FreemarkerService {

    /**
     * 编译模板
     *
     * @param tip 提示
     * @param content 模板内容
     * @param dataMap 数据
     * @return String
     * @throws BusinessException BusinessException
     */
    public String compile(String tip, String content, Map<String, Object> dataMap) throws BusinessException {
        try {
            StringWriter out = new StringWriter();
            Configuration configuration = this.getConfiguration();
            new Template(tip, new StringReader(content), configuration).process(dataMap, out);
            return out.toString();
        } catch (TemplateException e) {
            Map<String, String> errorData = new HashMap<>();
            errorData.put("position", tip);
            errorData.put("message", e.getMessage());
            throw new BusinessException(ResponseStatus.TEMPLATE_ERROR, errorData);
        } catch (ParseException e) {
            Map<String, String> errorData = new HashMap<>();
            errorData.put("position", tip);
            errorData.put("message", e.getMessage());
            throw new BusinessException(ResponseStatus.TEMPLATE_ERROR, errorData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(ResponseStatus.SERVER_ERROR);
        }
    }

    /**
     * 获取配置项
     */
    private Configuration getConfiguration () {
        return new Configuration(Configuration.VERSION_2_3_28);
    }
}
